package com.platform.common.utils;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.hibernate.validator.internal.engine.ValidatorImpl;

/**
 * 功能：
 * 
 * @author gaowei enterprise application platform version 0.1
 */
public class ValidationUtils {
	
	/**
	 * <pre>
	 * 功能：java Bean 对象验证
	 * </pre>
	 * 
	 * @param obj
	 * @return
	 */
	public static String validateObject(Object obj) {
		
		//用于存储验证后的错误信息
		StringBuffer buffer = new StringBuffer(64);
		Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
		Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);
		Iterator<ConstraintViolation<Object>> iter = constraintViolations.iterator();
		while (iter.hasNext()) {
			String message = iter.next().getMessage();
			buffer.append(message);
		}
		return buffer.toString();
	}
	
	/**
	 * <pre>
	 * 功能：对象方法参数验证
	 * </pre>
	 * 
	 * @param obj
	 * @param method
	 * @param parameterValues
	 * @return
	 */
	public static String validateParameters(Object obj, Method method, Object[] parameterValues) {
		// 用于存储验证后的错误信息
		StringBuffer buffer = new StringBuffer(64);
		ValidatorImpl validator = (ValidatorImpl) Validation.buildDefaultValidatorFactory().getValidator();
		Set<ConstraintViolation<Object>> constraintViolations = validator.validateParameters(obj, method, parameterValues);
		Iterator<ConstraintViolation<Object>> iter = constraintViolations.iterator();
		while (iter.hasNext()) {
			String message = iter.next().getMessage();
			buffer.append(message);
		}
		return buffer.toString();
	}
	
}
